參考資料:
Alex老師教學
JS30-Day14-JS Reference VS Copy
傳值和傳址的練習。
我對這部分的概念還不算很清楚,以後還需要繼續找題目來寫。
今天的練習都是開console看。
Q1
// start with strings, numbers and booleans
// 首先從字串、數字、布林開始
let a = 'A';
let b = a;
a = 'B';
console.log(a, b); // B A
let c = 0;
let d = c;
c++;
console.log(c, d); //1 0
let e = true;
let f = e;
e = false;
console.log(e, f); //false true
let g = 'A';
let h = 'A';
let i = 'A';
(h = 'B'), (i = 'C'), (g += h), (g += i);
// h = 'B';
// i = 'C';
// g += h;
// g += i;
console.log(g, h, i); //ABC B C
Q2
// Let's say we have an array
// 讓我們來看看陣列
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];//題目預設
// and we want to make a copy of it.
// 我們希望複製陣列
如果直接複製陣列,則複製後的陣列修改時會導致原始陣列也會改變,因為兩者指向同一儲存位置。
let players2 = players;
players2[0] = 'aaa';
console.log(players, players2);
所以我們需要使用其他方法做出新陣列,以下是兩種方法
let players3 = players.slice();
//slice()會把切出來的內容再做成一個陣列
players3[0] = 'bbb';
console.log(players, players3);
let players4 = [...players];
players4[1] = 'ccc';
console.log(players,players4);
Q3
// The same thing goes for objects, let's say we have a person object with Objects
// 處理物件也是類似的觀念
let person = { //題目預設
name: 'Wes Bos',
age: 80,
};
同樣的直接複製並修改會干擾到原本的物件
let person2 = person;
person.name = 'yyy';
console.log(person, person2);// {name: "yyy", age: 80} {name: "yyy", age: 80}
所以需要使用建立新物件的方法
let person3 = Object.assign({}, person);
person3.age = 30
console.log(person, person3);
物件有兩層的情況:
const abc = {
name: 'abc',
age: 100,
social: {
twitter: '@abc',
facebook: 'abc.developer',
},
};
用assign()
方法複製再修改仍會干擾到原始物件
let abc2 = Object.assign({}, abc);
abc2.social.facebook = null;
console.log(abc.social.facebook);//null
用JSON.parse(JSON.stringify())
則不會修改到原始物件
let abc3 = JSON.parse(JSON.stringify(abc));
abc3.social.facebook = null;
console.log(abc.social.facebook);